package com.powernode.aspect;

import com.powernode.annotation.DataScope;
import com.powernode.model.BaseQuery;
import com.powernode.util.AuthUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@Aspect
@Slf4j
public class DataScopeAspect {

    public static final String POINT_CUT = "@annotation(com.powernode.annotation.DataScope)";

    @Around(POINT_CUT)
    public Object before(ProceedingJoinPoint joinPoint) {
        Object result = null;
        // 获取目标方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 获取目标方法上的注解
        DataScope dataScopeAnnotation = signature.getMethod().getDeclaredAnnotation(DataScope.class);
        // 获取注解的属性
        String tableAlias = dataScopeAnnotation.tableAlias();
        String tableField = dataScopeAnnotation.tableField();

        // 获取当前登录用户的角色
        Set<String> roleList = AuthUtils.getSecurityUserRoleList();
        // 判断用户是否拥有管理员角色
        if (!roleList.contains("admin")) {
            // 当前用户角色中不包含管理员admin角色，则进行数据权限控制
            // 获取目标方法参数
            Object params = joinPoint.getArgs()[0];
            // 将目标方法参数转换为BaseQuery参数对象
            BaseQuery baseQuery = (BaseQuery) params;
            // 获取登录用户ID
            Integer userId = AuthUtils.getLoginUserId();
            // and tu.id = #{id}
            baseQuery.setFilterSQL("and "+tableAlias+"."+tableField+" = "+userId);
        }

        try {
            // 执行目标方法
            result = joinPoint.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }

        return result;
    }

}
